extends Reference
class_name Watcher
var _valueType=0 #0 基础数据  1 监听函数
var _value=null
var _valueFn=null
var _notifyList=[]
var _callBackList=[]
var _interVal=1 #主动监测时用的
var _intervalCounter=0
var disposed=false
var value setget set_value,get_value

func start(baseValue):
	_valueType=0
	_value=baseValue
	return self
func start2(target,fn):
	_valueType=1
	_valueFn=funcref(target,fn)
	calValue()
	return self
func set_value(value):
	if _valueType==0:
		_set_value(value)
	else:
		print('不要对计算watcher直接设置value')
func _set_value(v):
	if _value==v:
		return
	var pre=_value
	_value=v
	#触发事件
	var arr=_callBackList.duplicate()
	for fn in arr:
		if fn.is_valid():
			fn.call_func(_value,pre)
		else:
			_callBackList.erase(fn)
	#发送通知
	var l=_notifyList.duplicate()
	for w in l:
		if w.disposed:
			_notifyList.erase(w)
		elif W.is_wait:
			W.waitQueue.erase(w) #如果队列中已经有了，先从队列中删掉,然后再添加，保证是在最后一个
			W.waitQueue.append(w)
		else:
			w.calValue()
func onChange(target,fnStr,runNow=true):
	if disposed:
		return
	var fn=funcref(target,fnStr)
	_callBackList.append(fn)
	if runNow:
		fn.call_func(_value,_value)
	return self
func get_value():
	var w=W.activeWatcher()
	if w and !_notifyList.has(w) and !disposed:
		_notifyList.append(w)
	return _value
func calValue():
	if _valueType!=1:
		return
	if _valueFn.is_valid(): 
		W.stack.append(self)
		var v=_valueFn.call_func()
		W.stack.pop_back()
		_set_value(v)
	else:#如果对象被销毁了，销毁自己
		dispose()
func update():
	calValue()
func startDetect(interVal=1):
	if disposed:
		return
	if _valueType!=1:
		return
	_interVal=interVal
	if !W.detectList.has(self):
		W.detectList.append(self)
	return self
func stopDetect():
	W.detectList.erase(self)
func updateDetect():
	_intervalCounter+=1
	if _intervalCounter>=_interVal:
		_intervalCounter=0
		calValue()
func dispose():
	disposed=true
	stopDetect()
	_notifyList.clear()
	_callBackList.clear()

